<?php

namespace app\merchant\controller;


use app\http\validates\user\RegisterValidates;
use app\merchant\model\system\Express;
use app\merchant\model\system\SystemAdmin;
use app\merchant\model\system\SystemConfig;
use app\merchant\model\system\SystemGroupData;
use app\Request;
use crmeb\services\JsonService;
use crmeb\services\UtilService;
use think\facade\Config;
use think\facade\Db;
use think\facade\Session;
use think\facade\Route as Url;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * 登录验证控制器
 * Class Login
 * @package app\merchant\controller
 */
class Login extends SystemBasic
{
    public $code_url = "http://shop.user2006.com";
    public function index()
    {
        $cities = Db::name('system_city')->where('level',0)->select();
        $this->assign('cities',$cities);
        return $this->fetch();
    }

    /**
     * 登录验证 + 验证码验证
     */
    public function verify()
    {
        if (!request()->isPost()) return $this->failed('请登陆!');
        list($account, $pwd, $verify) = UtilService::postMore([
            'account', 'pwd', 'verify'
        ], null, true);
        //检验验证码
        if (!captcha_check($verify)) return $this->failed('验证码错误，请重新输入');
        $error = Session::get('login_error') ?: ['num' => 0, 'time' => time()];
        $error['num'] = 0;
        if ($error['num'] >= 5 && $error['time'] > strtotime('- 5 minutes'))
            return $this->failed('错误次数过多,请稍候再试!');
        //检验帐号密码
        $res = SystemAdmin::login($account, $pwd);

        if ($res) {
            Session::set('login_error', null);
            Session::save();
            return $this->successful(['url' => Url::buildUrl('Index/index')->build()]);
        } else {
            $error['num'] += 1;
            $error['time'] = time();
            Session::set('login_error', $error);
            Session::save();
            return $this->failed(SystemAdmin::getErrorInfo('用户名错误，请重新输入'));
        }
    }

    public function captcha()
    {
        ob_clean();
        return captcha();
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        SystemAdmin::clearLoginInfo();
        $this->redirect(Url::buildUrl('index')->build());
    }

    /**
     * 注册
     */
    public function register(){
        $cities = Db::name('system_city')->where('level',0)->select();
        $this->assign('cities',$cities);
        return $this->fetch();
    }

    /**
     * 注册
     */
    public function get_city(){
        $parent_id = \request()->param('parent_id');
        $cities = Db::name('system_city')->where('parent_id',$parent_id)->select();
        JsonService::successful('ok',$cities);
    }

    /**
     * 注册验证
     */
    public function do_register()
    {
        if (!request()->isPost()) return $this->failed('请登陆!');
        list($account, $pwd, $verify,$real_name,$invite_code,$company_name,$city_name) = UtilService::postMore([
            'account', 'pwd', 'verify','real_name','invite_code','company_name','city_name'
        ], null, true);
        //检验验证码
        $data_code = Db::name('sms_record')->where('phone',$account)->order("id desc")->value("content");
        if ($verify!=$data_code) return $this->failed('验证码错误，请重新输入');
        $is_have = Db::table('dl_member')->where('invite_code',$invite_code)->findOrEmpty();
        if(!$is_have){
            return $this->failed('邀请码错误');
        }
        $is_be = SystemAdmin::be(["account"=>$account]);
        if($is_be){
            return $this->failed('该手机号码已注册');
        }
        $insert['account'] = $account;
        $insert['pwd']     = md5($pwd);
        $insert['real_name']   = $real_name;
        $insert['invite_code'] = $invite_code;
        $insert['roles']       = 1;
        $insert['add_time']    = time();
        $insert['version']     = 1;
        $insert['status']      = 1;
        $insert['expire_time'] = time()+15*24*60*60;
        $insert['company_name'] = $company_name;
        $insert['city_name'] = $city_name;
        $result_id = Db::name('merchant_admin')->insertGetId($insert);
        if($result_id){
            $up['store_url'] = $this->code_url."?mer_id=".$result_id;
            Db::name('merchant_admin')->where('id',$result_id)->update($up);
            $this->create_config_data($result_id);
            $this->create_group_data($result_id);
            $this->create_express_data($result_id);
            return $this->successful("注册成功",['url' => Url::buildUrl('Login/index')->build()]);
        }else{
            return $this->failed('注册失败');
        }
    }

    /**
     * 创建配置数据
     */
    public  function create_config_data($mer_id){
        $is_have = SystemConfig::be(['mer_id'=>$mer_id]);
        if(!$is_have){
            $all_data = SystemConfig::where('mer_id',0)->select()->toArray();
            $insertAll = [];
            foreach ($all_data as $k=>$v){
                unset($all_data[$k]['id']);
                $all_data[$k]['mer_id'] = $mer_id;
                $insertAll[] = $all_data[$k];
            }
            $system_user_level_model = new SystemConfig();
            $system_user_level_model->saveAll($insertAll);
        }
    }

    /**
     * 创建数组数据
     */
    private function create_group_data($mer_id){
        $is_have = SystemGroupData::be(['mer_id'=>$mer_id]);
        if(!$is_have){
            $all_data = SystemGroupData::where('mer_id',0)->select()->toArray();
            $insertAll = [];
            foreach ($all_data as $k=>$v){
                unset($all_data[$k]['id']);
                $all_data[$k]['mer_id'] = $mer_id;
                $insertAll[] = $all_data[$k];
            }
            $system_user_level_model = new SystemGroupData();
            $system_user_level_model->saveAll($insertAll);
        }
    }

    /**
     * 创建快递数据
     */
    private function create_express_data($mer_id){
        $is_have = Express::be(['mer_id'=>$mer_id]);
        if(!$is_have){
            $all_data = Express::where('mer_id',0)->select()->toArray();
            $insertAll = [];
            foreach ($all_data as $k=>$v){
                unset($all_data[$k]['id']);
                $all_data[$k]['mer_id'] = $mer_id;
                $insertAll[] = $all_data[$k];
            }
            $system_user_level_model = new Express();
            $system_user_level_model->saveAll($insertAll);
        }
    }

    /**
     * 发送短信
     * @return stdClass
     */
    public function send_msg(Request $request) {
        $account = $request->param('account');
        //验证手机号
        try {
            validate(RegisterValidates::class)->scene('code')->check(['phone' => $account]);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        $userInfo = SystemAdmin::where('account', $account)->find();
        if ($userInfo) return app('json')->fail('账号已存在');
        //该号码今天发送发短信次数
        $today = strtotime(date("Y-m-d"));
        $map[] = ['phone','=',$account];
        $map[] = ['add_time','>',$today];
        $count = Db::name('sms_record')->where($map)->count();
        if($count>=5){
            return app('json')->fail('今日发送短信超过最大次数');
        }
        $code   = rand(1111,9999);
        $result = $this->do_send_msg($account,$code);
        if($result){
            $insert['phone']   = $account;
            $insert['content']  = $code;
            $insert['add_time'] = time();
            $insert['add_ip']   = \request()->ip();
            $insert['resultcode'] = "OK";
            $insert['record_id'] = time();
            Db::name('sms_record')->insert($insert);
            return app('json')->successful('发送成功');
        }else{
            return app('json')->fail('发送失败');
        }
    }

    /**
     * 发送短信
     * @return stdClass
     */
    public function send_msg_forget(Request $request) {
        $account = $request->param('account');
        //验证手机号
        try {
            validate(RegisterValidates::class)->scene('code')->check(['phone' => $account]);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        $userInfo = SystemAdmin::where('account', $account)->find();
        if (!$userInfo) return app('json')->fail('账号不存在');
        //该号码今天发送发短信次数
        $today = strtotime(date("Y-m-d"));
        $map[] = ['phone','=',$account];
        $map[] = ['add_time','>',$today];
        $count = Db::name('sms_record')->where($map)->count();
        if($count>=5){
            return app('json')->fail('今日发送短信超过最大次数');
        }
        $code   = rand(1111,9999);
        $result = $this->do_send_msg($account,$code);
        if($result){
            $insert['phone']   = $account;
            $insert['content']  = $code;
            $insert['add_time'] = time();
            $insert['add_ip']   = \request()->ip();
            $insert['resultcode'] = "OK";
            $insert['record_id'] = time();
            Db::name('sms_record')->insert($insert);
            return app('json')->successful('发送成功');
        }else{
            return app('json')->fail('发送失败');
        }
    }


    /**
     * 发送短信
     * @return stdClass
     */
    public function do_send_msg($phone,$code) {

        $code_json = json_encode(['code'=>$code]);
        AlibabaCloud::accessKeyClient('LTAI4GKi7hPkTvMzS1hYxPE9', 'NtheM3qkRzr3AeuUfjlWHknMvm2ac5')
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $phone,
                        'SignName' => "思客多",
                        'TemplateCode' => "SMS_192640507",
                        'TemplateParam' => $code_json,
                    ],
                ])
                ->request();
            $back = $result->toArray();
            if($back['Code']=="OK"){
               return true;
            }else{
               return false;
            }
        } catch (ClientException $e) {
            return false;
        } catch (ServerException $e) {
            return false;
        }
    }
    
    /**
     * 忘记密码
     */
    public function forget_password(){
        if(request()->isPost()){
            list($account, $pwd, $verify) = UtilService::postMore([
                'account', 'pwd', 'verify'
            ], null, true);
            //检验验证码
            $data_code = Db::name('sms_record')->where('phone',$account)->order("id desc")->value("content");
            if ($verify!=$data_code) return $this->failed('验证码错误，请重新输入');
            $is_be = SystemAdmin::be(["account"=>$account]);
            if(!$is_be){
                return $this->failed('该用户不存在');
            }
            $insert['pwd']     = md5($pwd);
            $result         = Db::name('merchant_admin')->where('account',$account)->update($insert);
            if($result){
                return $this->successful("操作成功",['url' => Url::buildUrl('Login/index')->build()]);
            }else{
                return $this->successful("操作成功",['url' => Url::buildUrl('Login/index')->build()]);
            }
        }else {
            return $this->fetch();
        }
    }

    /**
     * 用户协议
     */
    public function agreement(){
        return $this->fetch();
    }

    /**
     * 隐私协议
     */
    public function secrecy(){
        return $this->fetch();
    }

}